
var visibleAscii = "^[\\u0020-\\u007e]*$";

$(document).ready(function () {
    $.validator.setDefaults({
        errorClass: "uk-text-danger",
        errorPlacement: function (error, element) {
            error.insertAfter(element.parent("div"));
        },
        highlight: function (element, errorClass, validClass) {
            $(element).addClass("uk-form-danger");
        },
        unhighlight: function (element, errorClass, validClass) {
            $(element).removeClass("uk-form-danger");
        }
    });

    $('#form_psw_box').validate({
        rules: {
            'old_password:string': {
                required: true,
                pattern: visibleAscii,
                rangelength: [6, 64]
            },
            'new_password:string': {
                required: true,
                pattern: visibleAscii,
                rangelength: [6, 64]
            },
            'confirmation:skip': {
                required: true,
                pattern: visibleAscii,
                rangelength: [6, 64],
                equalTo: '#new_password'
            }
        },
        messages: {
            'old_password:string': {
                required: '此项必填',
                pattern: '不能包含特殊字符，如中文字符、希腊字母等',
                rangelength: '密码长度限定为 6-64 个字符'
            },
            'new_password:string': {
                required: '此项必填',
                pattern: '不能包含特殊字符，如中文字符、希腊字母等',
                rangelength: '密码长度限定为 6-64 个字符'
            },
            'confirmation:skip': {
                required: '此项必填',
                pattern: '不能包含特殊字符，如中文字符、希腊字母等',
                rangelength: '密码长度限定为 6-64 个字符',
                equalTo: '两次输入的新密码不同'
            }
        }
    });

    $('#btn_save_psw').click(onPasswordSave);
});

var blockingModal;
function onPasswordSave() {
    var form = $('#form_psw_box');
    if (!form.valid())
        return;

    blockingModal = UIkit.modal.blockUI('正在提交修改...');
    $.ajax({
        url: '/api/auth/update_password',
        data: form.serializeJSON(),
        type: 'POST'
    })
        .done(function () {
            blockingModal.hide();
            blockingModal = UIkit.modal.blockUI('修改成功，即将刷新页面...');
            setTimeout(function (args) { location.reload() }, 3000);
        })
        .fail(function (jqXHR) {
            try {
                var response = JSON.parse(jqXHR.responseText);
                if (response != null && response.error != null) {
                    UIkit.modal.alert("Error: " + response.error.message);
                } else {
                    UIkit.modal.alert("Error occurred.")
                }
            } catch (e) {
                UIkit.modal.alert("Error occurred.");
                console.error(e);
            } finally {
                blockingModal.hide();
            }
        })
}